//
//  XQJSHelper.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/2/4.
//

import UIKit
import WebKit
import StoreKit

class XQJSHelper: NSObject {
    
    weak var webController : XQBaseController!
    
    weak var configuration : WKWebViewConfiguration!
    
    var startTime : Int64 = 0
    
    init(viewController: XQBaseController, configuration: WKWebViewConfiguration) {
        super.init()
        
        self.webController = viewController
        self.configuration = configuration

        addConfiguration()
    }
    
    deinit {
        self.configuration.userContentController.removeScriptMessageHandler(forName: "MetaanalysesAsia")
        self.configuration.userContentController.removeScriptMessageHandler(forName: "ThanHas")
        self.configuration.userContentController.removeScriptMessageHandler(forName: "WithMany")
        self.configuration.userContentController.removeScriptMessageHandler(forName: "MoreTv")
        self.configuration.userContentController.removeScriptMessageHandler(forName: "StcenturySkin")
        self.configuration.userContentController.removeScriptMessageHandler(forName: "ThatOf")
        self.configuration.userContentController.removeScriptMessageHandler(forName: "HasAnd")
        self.configuration.userContentController.removeScriptMessageHandler(forName: "ThereTheir")
        
        self.configuration.userContentController.removeScriptMessageHandler(forName: "EmbraceAre")
        self.configuration.userContentController.removeScriptMessageHandler(forName: "AndNatural")
        self.configuration.userContentController.removeScriptMessageHandler(forName: "IdentitiesAre")
    }
    
    private func addConfiguration() {
        self.configuration.userContentController.add(self, name: "MetaanalysesAsia")
        self.configuration.userContentController.add(self, name: "ThanHas")
        self.configuration.userContentController.add(self, name: "WithMany")
        self.configuration.userContentController.add(self, name: "MoreTv")
        self.configuration.userContentController.add(self, name: "StcenturySkin")
        self.configuration.userContentController.add(self, name: "ThatOf")
        self.configuration.userContentController.add(self, name: "HasAnd")
        self.configuration.userContentController.add(self, name: "ThereTheir")
        
        self.configuration.userContentController.add(self, name: "EmbraceAre")
        self.configuration.userContentController.add(self, name: "AndNatural")
        self.configuration.userContentController.add(self, name: "IdentitiesAre")
    }
}

extension XQJSHelper : WKScriptMessageHandler{
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
       switch message.name {
       case "MetaanalysesAsia","WithMany" :
           jumpOtherController(datas: message.body)
           break
       case "ThanHas":
           close()
           break
       case "MoreTv":
           close()
           XQRouteTool.jumpHome()
           break
       case "StcenturySkin":
           close()
           XQRouteTool.jumpMine()
           break
       case "ThatOf":
           jumpLoginController()
           break
       case "HasAnd":
           telPhone(datas: message.body)
           break
       case "ThereTheir":
           popStoreView()
           break
       case "EmbraceAre":
           addMobState(datas: message.body)
           break
       case "AndNatural":
           startBindCard()
           break
       case "IdentitiesAre":
           endBindCard()
           break
       default:
           break
       }
   }
}

extension XQJSHelper {
    private func jumpOtherController (datas : Any) {
        if let body = datas as? [Any] {
            let datas = body
            if let url = datas.first as? String {
                XQRouteTool.jumpController(controller:webController, url: url)
            }
        }
    }
    
    private func close() {
        self.webController.navigationController?.popViewController(animated: true)
    }
    
    private func jumpLoginController() {
        
        self.webController.navigationController?.popToRootViewController(animated: false)
        XQRouteTool.jumpLogin()
    }
    
    private func telPhone(datas : Any) {
        if let body = datas as? [Any] {
            let datas = body
            if let phone = datas.first as? String {
                guard let url = URL(string: "tel://\(phone)"),
                      UIApplication.shared.canOpenURL(url) else {
                    return
                }
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }
    }
    
    private func popStoreView() {
        DispatchQueue.main.async {
            if let currentScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
                SKStoreReviewController.requestReview(in: currentScene)
            }
        }        
    }
    
    private func addMobState(datas : Any) {
        if let body = datas as? [Any] {
            let datas = body
            if let orderId = datas.first{
                var orderIdStr : String = ""
                if (orderId is Int) {
                    orderIdStr = "\(orderId)"
                }else if (orderId is String){
                    orderIdStr = orderId as! String
                }
                let time = XQTimeTool.nowTime()
                XQAnalysisManager.shared.notifyRisk(numberType: "10", longitude: self.webController.longitude, latitude: self.webController.latitude, startT: time, endT: time, orderId:orderIdStr)
            }
        }
    }
    
    private func startBindCard() {
        self.startTime = XQTimeTool.nowTime()
    }
    
    private func endBindCard() {
        let endTime = XQTimeTool.nowTime()
        XQAnalysisManager.shared.notifyRisk(numberType: "8", longitude: self.webController.longitude, latitude: self.webController.latitude, startT: self.startTime, endT: endTime, orderId: "")
    }
}
